package com.jhgsys.internal.hazard.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.hazard.constant.HazardConstant;
import com.jhgsys.internal.hazard.dto.HazardReportDto;
import com.jhgsys.internal.hazard.entity.HazardModuleConfig;
import com.jhgsys.internal.hazard.entity.HazardReport;
import com.jhgsys.internal.hazard.service.IHazardModuleConfigService;
import com.jhgsys.internal.hazard.service.IHazardReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/**
 * @Author wanghw
 * @CreateTime 2024/8/21 15:59
 * @Description 隐患整改审核
 * @Version 1.0
 */
@Slf4j
@Validated
@Controller
public class HazardReportAuditController extends BaseController {
    @Autowired
    private IHazardReportService hazardReportService;

    @Autowired
    private IHazardModuleConfigService hazardModuleConfigService;


    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardReportAudit")
    @RequiresPermissions("hazardReportAudit:view")
    public String hazardReportAuditIndex(Model model){
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("tenantList",getTenantList());
        model.addAttribute("currentTenantId", getCurrentTenantId());
        return FebsUtil.view("hazard/hazardReportAudit/hazardReportAuditList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardReportAudit/audit/{id}")
    @RequiresPermissions("hazardReportAudit:audit")
    public String hazardReportUpdate(Model model, @PathVariable("id") String id) throws JsonProcessingException {
        HazardReportDto dto = hazardReportService.findHazardReportById(id);
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("hazardReport", JSON.parse(new ObjectMapper().writeValueAsString(dto)));
        model.addAttribute("currentTenantId", getCurrentTenantId());
        HazardModuleConfig config = hazardModuleConfigService.findHazardModuleConfigByTenantId(getCurrentTenantId());
        if(ObjectUtils.isNotEmpty(config) && config.getSingleScore() !=0){
            model.addAttribute("singleScore", config.getSingleScore());
        }else {
            model.addAttribute("singleScore", 0);
        }
        return FebsUtil.view("hazard/hazardReportAudit/hazardReportAuditEdit");
    }

    /**
     * 隐患待审核查询（分页）
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @GetMapping("hazardReportAudit/list")
    @ResponseBody
    @RequiresPermissions("hazardReportAudit:view")
    public FebsResponse hazardReportList(QueryRequest request, HazardReportDto hazardReport) {
        hazardReport.setStatus(HazardConstant.HAZARD_STATUS.WAITING_AUDIT);
        Map<String, Object> dataTable = getDataTable(this.hazardReportService.findHazardReportPage(request, hazardReport));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 隐患审核
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @Log("隐患审核")
    @PostMapping("hazardReportRectificationAudit")
    @ResponseBody
    @RequiresPermissions("hazardReportAudit:audit")
    public FebsResponse submitHazardReportRectification(@RequestBody  HazardReportDto hazardReport) throws FebsException {
        try {
            checkParams(hazardReport);
            HazardReport report = hazardReportService.findHazardReportById(hazardReport.getReportId());
            if(ObjectUtils.isEmpty(report)){
                return new FebsResponse().fail().message("待审核的隐患信息不存在!");
            }
            if (!HazardConstant.HAZARD_STATUS.WAITING_AUDIT.equals(report.getStatus())){
                return new FebsResponse().fail().message("该隐患信息已经审核过！");
            }

            HazardModuleConfig config = hazardModuleConfigService.findHazardModuleConfigByTenantId(getCurrentTenantId());
            if(ObjectUtils.isNotEmpty(config) && config.getMaxYearScore() !=0){
                Map<String, Object> countInfo = this.hazardReportService.countYearByUserName(report.getCreatedBy());
                log.info("{}本年度累计获得奖励积分{}",report.getCreatedBy(),countInfo);
                int bonusPoints = Integer.parseInt((String) countInfo.get("bonusPoints"))  + hazardReport.getBonusPoints();
                if(config.getMaxYearScore()< bonusPoints){
                    throw new FebsException("该人当年获得积分已达年度上限！");
                }
            }

            hazardReport.setUpdatedBy(getCurrentUser().getUserName());
            hazardReport.setUpdatedTime(new Date());
            hazardReport.setAuditDate(new Date());
            hazardReport.setAuditUserId(getCurrentUser().getUserId());
            hazardReport.setAuditRealName(getCurrentUser().getUname());
            this.hazardReportService.saveHazardReportAuditRecord(hazardReport,getCurrentUser());
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "审核隐患信息失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    private void checkParams( HazardReportDto hazardReport) throws FebsException {
        if(StringUtils.isBlank(hazardReport.getReportId())){
            throw new FebsException("隐患报告ID不能为空");
        }

        if(StringUtils.isBlank(hazardReport.getStatus())){
            throw new FebsException("状态不能为空");
        }

        if(!HazardConstant.HAZARD_STATUS.WAITING_ISSUANCE.equals(hazardReport.getStatus())
              && !HazardConstant.HAZARD_STATUS.BACK_AUDIT.equals(hazardReport.getStatus())){
            throw new FebsException("非法状态");
        }

        if(HazardConstant.HAZARD_STATUS.WAITING_ISSUANCE.equals(hazardReport.getStatus())){
            if(ObjectUtils.isEmpty(hazardReport.getBonusPoints())){
                throw new FebsException("奖励积分不能为空");
            }
            if(StringUtils.isBlank(hazardReport.getNearmissFlg())){
                throw new FebsException("nearMiss不能为空");
            }
        }

        if(HazardConstant.HAZARD_STATUS.BACK_AUDIT.equals(hazardReport.getStatus())){
            if(ObjectUtils.isEmpty(hazardReport.getAuditRemark())){
                throw new FebsException("审核退回备注不能为空");
            }
        }

    }


}
